package com.ukao.cashregister.ui.packPackag;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gprinterio.GpDevice;
import com.ukao.cashregister.R;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.ProductRelImgBean;
import com.ukao.cashregister.bean.ReceiptBean;
import com.ukao.cashregister.bean.RecheckBean;
import com.ukao.cashregister.bean.StrikeBean;
import com.ukao.cashregister.bean.StringBean;
import com.ukao.cashregister.eventbus.MembershipCardEvent;
import com.ukao.cashregister.pesenter.PackPackagPesenter;
import com.ukao.cashregister.printer.PrintMiuiHelper;
import com.ukao.cashregister.printer.PrinterHelper;
import com.ukao.cashregister.printer.PrinterReceipt;
import com.ukao.cashregister.ui.MainActivity;
import com.ukao.cashregister.ui.clothinQuery.PhotoActivity;
import com.ukao.cashregister.usbrfidreader.UsbrfidreaderHelper;
import com.ukao.cashregister.utils.CheckUsbDeviceUtils;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.KeyBoardUtil;
import com.ukao.cashregister.utils.SystemUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.PackPackagView;
import com.ukao.cashregister.widget.ClearEditText;
import com.ukao.cashregister.widget.PercentLinearLayout;
import com.ukao.cashregister.widget.StateButton;
import com.ukao.cashregister.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.rewashing_btn;
import static com.ukao.cashregister.R.id.strike_btn;


public class packPackagFragment extends MvpFragment<PackPackagPesenter> implements PackPackagView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.search_edit_text)
    ClearEditText searchEditText;
    Unbinder unbinder;
    @BindView(R.id.search_button)
    StateImageView searchButton;
    @BindView(R.id.statusText)
    TextView statusText;
    @BindView(R.id.factoryName)
    TextView factoryName;
    @BindView(R.id.productName)
    TextView productName;
    @BindView(R.id.serviceName)
    TextView serviceName;
    @BindView(R.id.addServiceDesc)
    TextView addServiceDesc;
    @BindView(R.id.annexDesc)
    TextView annexDesc;
    @BindView(R.id.productImgCnt)
    TextView productImgCnt;
    @BindView(R.id.productImgCnt_btn)
    StateImageView productImgCntBtn;
    @BindView(R.id.brandName)
    TextView brandName;
    @BindView(R.id.colorDesc)
    TextView colorDesc;
    @BindView(R.id.flawDesc)
    TextView flawDesc;
    @BindView(R.id.effectDesc)
    TextView effectDesc;
    @BindView(R.id.center_layout)
    PercentLinearLayout centerLayout;
    @BindView(R.id.operating_txt)
    TextView operatingTxt;
    @BindView(rewashing_btn)
    StateButton rewashingBtn;
    @BindView(strike_btn)
    StateButton strikeBtn;
    @BindView(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.layout)
    LinearLayout layout;
    @BindView(R.id.print_btn)
    StateButton printBtn;
    @BindView(R.id.rfid_btn)
    StateImageView rfidBtn;



    private String mParam1;
    private String mParam2;
    private RecheckBean.ProductInfoBean mProListBean;
    private ArrayList<StringBean> mAnnexDesclist;
    private ArrayList<StringBean> meffectDesclist;
    private ArrayList<StringBean> mflawDesclist;
    private ArrayList<StringBean> mColorDesclist;
    private String strScanCode;
    private   ArrayList<String>  mPhotoData=new ArrayList<>();

    private String strScanCodeId;

    public static packPackagFragment newInstance(String param1, String param2) {
        packPackagFragment fragment = new packPackagFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected PackPackagPesenter createPresenter() {
        return new PackPackagPesenter(this);
    }

    @Override
    protected void initView() {
        UsbrfidreaderHelper.getInstance().readCardNum();
        searchEditText.requestFocus();
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(MembershipCardEvent event) {

        switch (event.getMessage()) {
            case add:/*成功*/
                String rfidSecretCard = (String) event.getData();
                searchEditText.setText(rfidSecretCard);
                searchScanCode();
                break;






        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_pack_packag, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initListener() {
        super.initListener();
        searchEditText.setOnEditorActionListener(mOnEditorAction);

    }


    TextView.OnEditorActionListener mOnEditorAction = (v, actionId, event) -> {
        if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
            searchScanCode();
        }
        return false;
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        UsbrfidreaderHelper.getInstance().cancelReadCardNum();
        unbinder.unbind();
    }

    @OnClick({R.id.search_button, rewashing_btn, strike_btn, R.id.print_btn,R.id.productImgCnt_btn,R.id.rfid_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case  R.id.rfid_btn:
                UsbrfidreaderHelper.getInstance().readCardNum();
                break;
            case R.id.print_btn:
                if (CheckUtils.isMIUIDevices()){
                    mvpPresenter.printReceipt(_mActivity, mProListBean.getOrderId() + "");
                }else if (CheckUsbDeviceUtils.isReceipt()) {/*小票*/
                    mvpPresenter.printReceipt(_mActivity, mProListBean.getOrderId() + "");

                }

                break;

            case R.id.search_button:

                searchScanCode();
                hideSoftInput();

                break;
            case rewashing_btn:
                if (CheckUtils.isEmpty(strScanCodeId))return;
                mvpPresenter.stockRework(strScanCodeId);

                break;
            case strike_btn:/*合格標*/
                if (!CheckUtils.isEmpty(strScanCodeId))
                    mvpPresenter.conformity(_mActivity, strScanCodeId);


                break;
            case  R.id.productImgCnt_btn : /*查看图片*/
                if (CheckUtils.isEmpty(mPhotoData))return;
                Intent mIntent=new Intent(_mActivity,PhotoActivity.class);
                mIntent.putStringArrayListExtra(ARG_PARAM1,mPhotoData);
                mIntent.putExtra(ARG_PARAM2,0);
                startActivity(mIntent);
                break;



        }
    }

    private void searchScanCode() {
        String strscanCode = getText(searchEditText);
        if (strscanCode.isEmpty()) return;
        mvpPresenter.stationScanCode(_mActivity, strscanCode);
    }

    @Override
    public void loadSearchData(RecheckBean mRecheckBean) {

        cleanCode();
        centerLayout.setVisibility(View.VISIBLE);
        bottomLayout.setVisibility(View.VISIBLE);
        mProListBean = mRecheckBean.getProductInfo();
        strScanCode = mProListBean.getScanCode();
        strScanCodeId = mProListBean.getId();
        if (mRecheckBean.isPrint()){
            mvpPresenter.conformity(_mActivity, strScanCodeId);

        }

        mPhotoData.clear();
        List<ProductRelImgBean> mProductImgData = mRecheckBean.getProductImgList();
        for (ProductRelImgBean productRelImgBean : mProductImgData) {
            mPhotoData.add(productRelImgBean.getCameraImg());
        }

        statusText.setText(CheckUtils.isEmptyString(mProListBean.getStatusText()));
        String  storeName=CheckUtils.isEmptyString(mProListBean.getStoreName());
        factoryName.setText(CheckUtils.isEmptyString(mProListBean.getMark())+" "+storeName);
        productName.setText(mProListBean.getProductName());
        serviceName.setText(mProListBean.getServiceName());
        brandName.setText(CheckUtils.isEmptyString(mProListBean.getBrandName()));
        productImgCnt.setText(CheckUtils.isEmptyString(mProListBean.getProductImgCnt()));


        Gson mGson = new Gson();
        if (!CheckUtils.isEmpty(mProListBean.getAddServiceDesc())) {
            List<StringBean> mServiceDesclist = mGson.fromJson(mProListBean.getAddServiceDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String service = "";
            for (StringBean item : mServiceDesclist) {
                service = service + item.getName() + CheckUtils.isEmptyNumber(item.getAmt()) + "元" + ",";
            }
            if (service.endsWith(","))
                service = service.substring(0, service.length() - 1);
            addServiceDesc.setText(service); /* 附加f服务  */
        } else {
            addServiceDesc.setText("");
        }
        rewashingBtn.setVisibility( mProListBean.getHasRefund()!=0?View.GONE:View.VISIBLE);/*1代表已經退洗*/
        if (!CheckUtils.isEmpty(mProListBean.getAnnexDesc())) {
            mAnnexDesclist = mGson.fromJson(mProListBean.getAnnexDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String annex = "";
            for (StringBean item : mAnnexDesclist) {
                annex = annex + item.getName() + "/";

            }
            if (annex.endsWith("/"))
                annex = annex.substring(0, annex.length() - 1);
            annexDesc.setText(annex); /* 附件   */

        } else {
            annexDesc.setText("");
        }
        if (!CheckUtils.isEmpty(mProListBean.getColorDesc())) {
            mColorDesclist = mGson.fromJson(mProListBean.getColorDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String color = "";
            for (StringBean item : mColorDesclist) {
                color = color + item.getName() + "/";
            }
            if (color.endsWith("/"))
                color = color.substring(0, color.length() - 1);
            colorDesc.setText(color); /* 颜色  */
        } else {
            colorDesc.setText("");
        }

        if (!CheckUtils.isEmpty(mProListBean.getFlawDesc())) {
            mflawDesclist = mGson.fromJson(mProListBean.getFlawDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String strflawDesc = "";
            for (StringBean item : mflawDesclist) {
                strflawDesc = strflawDesc + item.getName() + "/";
            }
            if (strflawDesc.endsWith("/"))
                strflawDesc = strflawDesc.substring(0, strflawDesc.length() - 1);
            flawDesc.setText(strflawDesc); /*瑕疵*/
        } else {
            flawDesc.setText("");
        }
        if (!CheckUtils.isEmpty(mProListBean.getEffectDesc())) {
            meffectDesclist = mGson.fromJson(mProListBean.getEffectDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String streffectDesc = "";
            for (StringBean item : meffectDesclist) {
                streffectDesc = streffectDesc + item.getName() + "/";
            }
            if (streffectDesc.endsWith("/"))
                streffectDesc = streffectDesc.substring(0, streffectDesc.length() - 1);
            effectDesc.setText(streffectDesc); /*洗后效果*/
        } else {
            effectDesc.setText("");
        }




    }

    private void cleanCode() {
        searchEditText.setText("");
        searchEditText.requestFocus();
        SystemUtils.hideInputmethod(searchEditText);

    }


    @Override
    public void loadFail(String error) {
        T.show(error);
    }

    @Override
    public void loadReworkSucceed(String message) {
        T.show(message);
    }

    @Override
    public void loadReworkFail(String msg) {
        cleanCode();
        T.show(msg);
    }

    /**
     * 打合格
     *
     * @param mStrikeBean
     */
    @Override
    public void loadStrikeSucceed(StrikeBean mStrikeBean) {

        if (CheckUsbDeviceUtils.isTSCprinter()) {
            PrinterHelper.getInstance().printStrike(mStrikeBean);

        }
    }
    @Override
    public void loadReceipt(ReceiptBean mReceiptBean) {
        if (CheckUtils.isMIUIDevices()) {
            PrintMiuiHelper.receiptReceipt(MainActivity.getPrintService(),mReceiptBean );
        }else{
            PrinterReceipt mPrinterReceipt = new PrinterReceipt();
            GpDevice mDevice = new GpDevice();
            mPrinterReceipt.printGp80(mReceiptBean, mDevice);

        }

    }


}
